<template>
  <div class="related-box">
    <div class="app-container basicfile-box">
      <el-row :gutter="20">
        <el-col :xs="24" :sm="6" :md="6" :lg="4">
          <!-- 搜索 -->
          <el-input
            class="search-sort"
            v-model="searchName"
            placeholder="请输入分类名称"
            clearable
            size="small"
            prefix-icon="el-icon-search"
            style="margin-bottom: 10px"
          />
          <!-- 分类数据 -->
          <Tree
            ref="tree"
            :sortTree="sortTree"
            :isHeight="isHeight"
            :loading="loading"
            :isOperation="isOperation"
            @nodeClick="nodeClick(arguments)"
            :searchName="searchName"
          />
        </el-col>
        <!-- 搜索数据 -->
        <el-col :span="20" :xs="24">
          <el-form
            :inline="true"
            class="search-related"
            label-width="68px"
            style="margin-bottom: 15px"
            v-hasPermi="['inv:related:query']"
          >
            <el-form-item label="物料编码">
              <el-input
                v-model="searchForm.searchCode"
                clearable
                size="small"
                style="width: 240px"
              />
            </el-form-item>
            <el-form-item label="物料名称">
              <el-input
                v-model="searchForm.searchName"
                clearable
                size="small"
                style="width: 240px"
              />
            </el-form-item>
            <el-form-item>
              <el-button
                type="primary"
                v-hasPermi="['inv:related:query']"
                icon="el-icon-search"
                @click="search"
                size="mini"
                >搜索</el-button
              >
              <el-button
                icon="el-icon-refresh"
                v-hasPermi="['inv:related:query']"
                size="mini"
                @click="serchReset()"
                >重置
              </el-button>
            </el-form-item>
          </el-form>
          <el-row :gutter="10" class="mb8 operation-btn">
            <el-col :span="1.5">
              <el-button
                type="primary"
                v-hasPermi="['inv:related:query']"
                plain
                icon="el-icon-menu"
                size="mini"
                @click="checkleAll"
                >查询所有</el-button
              >
            </el-col>
            <el-col :span="1.5">
              <el-button
                type="primary"
                plain
                icon="el-icon-circle-check"
                size="mini"
                @click="btnReview"
                :disabled="disCuarent"
                v-hasPermi="['inv:related:effc']"
                >核名</el-button
              >
            </el-col>
            <el-col :span="1.5">
              <el-button
                type="danger"
                plain
                icon="el-icon-remove-outline"
                size="mini"
                @click="handlEmpty"
                :disabled="disCuarent"
                v-hasPermi="['inv:related:dump']"
                >清空</el-button
              >
            </el-col>
            <el-col :span="1.5">
              <el-button
                type="info"
                plain
                :disabled="disCuarent"
                icon="el-icon-upload2"
                size="mini"
                @click="handleImport2"
                v-hasPermi="['inv:related:import']"
                >导入</el-button
              >
            </el-col>
            <el-col :span="1.5">
              <span v-if="isDrawingNo == false">
                <el-button
                  type="warning"
                  plain
                  icon="el-icon-download"
                  size="mini"
                  @click="handleExportRelated"
                  v-hasPermi="['inv:related:export']"
                  >导出</el-button
                >
              </span>
              <span v-if="isDrawingNo == true">
                <el-button
                  type="warning"
                  plain
                  icon="el-icon-download"
                  size="mini"
                  @click="handleExportMach"
                  v-hasPermi="['inv:related:import']"
                  >导出</el-button
                >
              </span>
            </el-col>
            <el-col :span="1.5">
              <el-button
                type="success"
                plain
                icon="el-icon-printer"
                size="mini"
                @click="handlePrint"
                v-hasPermi="['inv:related:print']"
                >打印</el-button
              >
            </el-col>
          </el-row>
          <!-- 打印数据 -->
          <PrintPage
            :printData="printData"
            ref="startPrint"
            :title="printName"
          />
          <!-- 物料数据 -->
          <el-table
            v-loading="reLoading"
            :data="basicfileList"
            border
            :height="maxHeight"
          >
            <el-table-column
              type="index"
              width="60"
              align="center"
              label="序号"
            >
            </el-table-column>
            <el-table-column
              label="物料编码"
              align="center"
              sortable
              prop="code"
              width="280"
            >
              <template slot="header" slot-scope="scope">
                <div class="search-box">
                  <transition name="toggle-fade" class="no-print">
                    <div
                      class="box-input"
                      v-show="inputStatusCode"
                      @click.stop="return false;"
                    >
                      <div class="input-t">
                        <el-input
                          size="mini"
                          placeholder="请输入物料编码"
                          v-model="headerFrom.codeInput"
                          @keyup.enter.native="searchCodeName('code', scope)"
                        />
                      </div>
                    </div>
                  </transition>
                  <div class="search-header">
                    <span>物料编码</span>
                    <i
                      class="el-icon-search no-print"
                      v-hasPermi="['inv:related:query']"
                      @click.stop="handleCodeName('code')"
                      v-if="!inputStatusCode"
                    ></i>
                    <i
                      class="el-icon-close no-print"
                      v-hasPermi="['inv:related:query']"
                      @click.stop="handleClose('code')"
                      v-if="inputStatusCode"
                    ></i>
                  </div>
                </div>
              </template>
              <template slot-scope="scope">
                <span>{{ scope.row.code }}</span>
              </template>
            </el-table-column>
            <el-table-column
              label="物料名称"
              align="center"
              prop="name"
              sortable
            >
              <template slot="header" slot-scope="scope">
                <div class="search-box">
                  <transition name="toggle-fade">
                    <div
                      class="box-input"
                      v-show="inputStatusName"
                      @click.stop="return false;"
                    >
                      <div class="input-t">
                        <el-input
                          size="mini"
                          placeholder="请输入物料名称"
                          v-model="headerFrom.nameInput"
                          @keyup.enter.native="searchCodeName('name', scope)"
                        />
                      </div>
                    </div>
                  </transition>
                  <div class="search-header">
                    <span>物料名称</span>
                    <i
                      class="el-icon-search"
                      @click.stop="handleCodeName('name')"
                      v-if="!inputStatusName"
                    ></i>
                    <i
                      class="el-icon-close"
                      @click.stop="handleClose('name')"
                      v-if="inputStatusName"
                    ></i>
                  </div>
                </div>
              </template>
              <template slot-scope="scope">
                <span @click.stop="seeMaterial(scope.row)">{{
                  scope.row.name
                }}</span>
              </template>
            </el-table-column>
            <el-table-column
              :label="labelName"
              align="center"
              prop="attribute"
              width="200"
            />
            <el-table-column
              label="主计量"
              align="center"
              prop="unitName"
              width="75"
            />
            <el-table-column
              label="图纸号"
              align="center"
              prop="drawingNo"
              v-if="isDrawingNo"
              width="200"
            />
            <el-table-column
              label="操作"
              align="center"
              class-name="small-padding"
              width="150"
            >
              <template slot-scope="scope">
                <div class="public-btn">
                  <el-button
                    size="mini"
                    type="text"
                    class="basic-see"
                    @click.stop="seeMaterial(scope.row)"
                    v-hasPermi="['inv:related:view']"
                    >查看
                  </el-button>
                  <el-button
                    size="mini"
                    class="basic-delete"
                    type="text"
                    @click.stop="delMaterial(scope.row)"
                    v-hasPermi="['inv:related:remove']"
                    >删除
                  </el-button>
                </div>
              </template>
            </el-table-column>
          </el-table>
          <!-- 分页信息 -->
          <pagination
            v-show="total >= 19"
            :total="total"
            :page.sync="queryParams.pageNum"
            :limit.sync="queryParams.pageSize"
            @pagination="getMaterialList"
          />
        </el-col>
      </el-row>
      <el-dialog
        title="物料信息"
        :visible.sync="open"
        width="600px"
        v-if="open"
        @close="closeDialog"
      >
        <el-form
          ref="materialForm"
          :model="materialForm"
          label-width="80px"
          size="medium"
          :disabled="butChange == 'seeStatus'"
          :validate-on-rule-change="false"
          :hide-required-asterisk="star"
        >
          <el-row>
            <el-col :span="24">
              <el-form-item
                label="分类信息"
                prop="value"
                v-if="butChange == 'seeStatus'"
              >
                <el-cascader
                  v-model="value"
                  :options="sortTree"
                  ref="classTree"
                  :props="classProps"
                  class="cas-input"
                ></el-cascader>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="物料编码">
                <el-input
                  v-model="materialForm.code"
                  :disabled="true"
                ></el-input>
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item label="更新时间">
                <el-input
                  v-model="materialForm.updateTime"
                  class="updata-time"
                ></el-input>
              </el-form-item>
            </el-col>
            <!-- 左部开始 -->
            <el-col :span="12">
              <el-col :span="24">
                <el-form-item label="物料名称" prop="name">
                  <el-input v-model="materialForm.name"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="主计量">
                  <el-select
                    v-model="materialForm.unitCode"
                    placeholder="请选择"
                  >
                    <el-option
                      v-for="(item, index) in packingDate"
                      :key="index"
                      :label="item.name"
                      :value="item.code"
                    >
                      <span>{{ item.name }}</span>
                      <span>（{{ item.code }}）</span>
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item :label="labelName" prop="attribute">
                  <el-input v-model="materialForm.attribute"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="规格描述" prop="property">
                  <el-input v-model="materialForm.property"></el-input>
                </el-form-item>
              </el-col>
            </el-col>
            <!-- 左部结束 -->
            <!-- 右部开始 -->
            <el-col :span="12">
              <div style="overflow: hidden; margin-right: 10px">
                <div class="ma-right">
                  <el-col :span="24">
                    <el-form-item label="供应方式" prop="property">
                      <el-select
                        v-model="materialForm.supplyType"
                        placeholder=""
                      >
                        <el-option
                          v-for="item in optionsSupplyType"
                          :key="item.dictValue"
                          :label="item.dictLabel"
                          :value="item.dictValue"
                        >
                        </el-option>
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :span="24">
                    <el-form-item
                      label="图纸号"
                      prop="drawingNo"
                      v-if="isDrawingNo"
                    >
                      <el-input v-model="materialForm.drawingNo"></el-input>
                    </el-form-item>
                  </el-col>

                  <el-col :span="24">
                    <el-form-item
                      label="允许负库存"
                      prop="enableDebt"
                      style="text-align: right"
                    >
                      <el-switch
                        v-model="materialForm.enableDebt"
                        active-value="1"
                        inactive-value="0"
                      ></el-switch>
                    </el-form-item>
                  </el-col>
                </div>
              </div>
            </el-col>
            <!-- 右部结束 -->
          </el-row>
        </el-form>
        <!-- 物料数量表单 -->
        <div class="from-mount" v-if="butChange == 'seeStatus'">
          <el-form
            :model="materialMount"
            label-width="100px"
            size="medium"
            class="mount-form"
            disabled
          >
            <el-row>
              <el-col :span="12">
                <el-form-item label="当前库存数量" class="txt-right">
                  <el-input
                    v-model="materialMount.quantity"
                    class="now-stock"
                  ></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="实际可用数量" class="txt-right">
                  <el-input
                    v-model="materialMount.params.availableQuantity"
                    class="now-actual"
                  ></el-input>
                </el-form-item>
              </el-col>

              <el-col :span="12">
                <el-form-item label="锁定库存数量">
                  <el-input
                    v-model="materialMount.lockQuantity"
                    class="txt-right"
                  ></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="在途库存数量">
                  <el-input
                    v-model="materialMount.wayQuantity"
                    class="txt-right"
                  ></el-input>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </div>
      </el-dialog>
      <!-- 物料导入对话框 -->
      <el-dialog
        :title="upload2.title"
        :visible.sync="upload2.open"
        width="400px"
        append-to-body
      >
        <el-upload
          ref="upload2"
          :limit="1"
          accept=".xlsx, .xls"
          :headers="upload2.headers"
          :action="upload2.url + '?sortId=' + upload2.sortId"
          :disabled="upload2.isUploading"
          :on-progress="handleFileUploadProgress2"
          :on-success="handleFileSuccess2"
          :auto-upload="false"
          drag
        >
          <i class="el-icon-upload"></i>
          <div class="el-upload__text">
            将文件拖到此处，或
            <em>点击上传</em>
          </div>
          <div class="el-upload__tip" style="color: red" slot="tip">
            提示：仅允许导入“xls”或“xlsx”格式文件！
          </div>
        </el-upload>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="submitFileForm2">确 定</el-button>
          <el-button @click="upload2.open = false">取 消</el-button>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { getToken } from "@/utils/auth";
import axios from "axios";
import {
  listMaterial,
  emptyMaterial,
  deleteMaterial,
  listUnit,
  exportRelatedMaterial,
  exportMachiningMaterial,
  dictMatching,
  moduleParameters,
} from "../../api/items"; //物料接口
import { listSort } from "../../api/sort"; //分类接口
import { getTreeData, getEcho, isAccord } from "../../utils/items"; //js方法
import Tree from "../../components/Sort/tree"; //分类组件
import PrintPage from "../../components/Related/print"; //分类组件
import { supParent } from "../../utils/sort.js"; //打印获取分类名称
export default {
  name: "Related",
  data() {
    // 分类效验规则
    var checkValue = (rule, value, callback) => {
      if (this.value.length == 0) {
        return callback(new Error(""));
      } else {
        callback();
      }
    };

    // 期初数量效验规则
    var checkInitial = (rule, value, callback) => {
      if (!value && this.materialForm.initial !== 0) {
        return callback(new Error(""));
      }
      if (!isAccord(value)) {
        callback(new Error(""));
      } else {
        callback();
      }
    };
    // 主计量效验规则
    var checkPacking = (rule, value, callback) => {
      if (this.packingForm == "") {
        return callback(new Error(""));
      } else {
        callback();
      }
    };
    return {
      // 遮罩层
      loading: true,
      reLoading: true,
      // 窗口高度
      screenHeight: document.body.clientHeight,
      //分类搜索名称
      searchName: "",
      // 批量删除按钮状态
      multiple: true,
      //是否显示分类操作按钮
      isOperation: true,
      //树形数据
      sortTree: [],
      //规格名称
      labelName: "剂型",
      //树形选中是否高亮
      isHeight: true,
      //物料数据最大高度
      maxHeight: null,
      //参数配置sortId
      paramSort: {
        sortId: [],
        sortCode: [],
      },
      // 导入/导出/清空按钮状态
      disCuarent: true,
      // 是否保存弹框分类回显数据
      isSava: false,
      //点击分类树中转站
      transferData: {
        sortId: "",
        unitCode: "",
      },
      //供应方式
      optionsSupplyType: [],
      //搜索参数
      searchForm: {
        searchName: "", //搜索物料名称
        searchCode: "", //搜索物料编码
      },
      // 头部料品搜索
      headerFrom: {
        codeInput: "",
        nameInput: "",
      },
      //头部编码输入框状态
      inputStatusCode: false,
      inputStatusName: false,
      // 料品查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 100,
        sortId: "",
        invCode: "",
        type: true,
        sortRoot: "",
      },
      // 总条数
      total: 0,
      // 日期范围
      dateRange: [],
      // 料品数据
      basicfileList: [],
      // 新增/修改/编辑对话框状态
      open: false,
      //对话框标题
      dialogTitle: "",
      //必填是否显示*号
      star: false,
      //选择分类回显信息
      value: [],
      //表单禁用状态
      seeStatus: false,
      //分类选择配置
      classProps: {
        children: "children",
        label: "sortName",
        value: "sortCode",
        checkStrictly: true,
      },
      packingDate: [],
      // 主计量
      packingForm: "",
      // 物料新增/修改信息表单
      materialForm: {
        code: "",
        sortId: "",
        name: "",
        attribute: "",
        initial: "",
        price: "",
        place: "",
        children: [],
      },
      //是否显示图纸号
      isDrawingNo: false,
      // 物料导入参数
      upload2: {
        // 是否显示弹出层（物料信息导入）
        open: false,
        // 弹出层标题（物料信息导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        //分类id
        sortId: "",
        // 设置上传的请求头部
        headers: {
          Authorization: "Bearer " + getToken(),
        },
        // 上传的地址
        url: "",
      },
      // 核名地址
      effecUrl: process.env.VUE_APP_BASE_API + "/inv/items/checkName/",
      //打印分类名称
      printName: "",
      //打印数据
      printData: [],
      //打印状态
      printShow: false,
      //物料查看数量表单
      materialMount: {},
      //弹框提交按钮状态，addStatus（新增） updateStatus（修改） seeStatus 查看
      butChange: "",
      //更多状态
      moreStatus: true,
    };
  },
  created() {
    // 是否显示图纸号
    let path = this.$route.path;
    if (path.indexOf("mach") > -1) {
      this.isDrawingNo = true;
      this.upload2.url =
        process.env.VUE_APP_BASE_API + "/inv/items/import/mach";
      this.labelName = "规格型号";
    } else {
      this.isDrawingNo = false;
      this.upload2.url = process.env.VUE_APP_BASE_API + "/inv/items/import/tc";
      this.labelName = "剂型";
    }

    this.getTreeList().then(() => {
      this.getSupplyType();
      //初始化物料数据
      this.getMaterialList();
      // 初始化主计量
      this.getPacking();
    });
    //隐藏操作按钮
    this.isOperation = false;
  },

  methods: {
    //获取分类数据
    getTreeList() {
      return new Promise((resolve) => {
        this.loading = true;
        this.paramSort.sortCode = this.$route.query.sort.split(",");
        let acTree = [];
        listSort().then((res) => {
          if (res.code == 200) {
            if (res.data.length > 0 && this.paramSort.sortCode.length > 0) {
              this.paramSort.sortCode.forEach((code) => {
                res.data.forEach((item) => {
                  if (item.sortCode == code) {
                    this.paramSort.sortId.push(item.sortId);
                    acTree.push(item);
                  }
                });
              });
              this.sortTree = getTreeData(acTree); //当children为0时，赋值undefined
            } else {
              this.sortTree = [];
            }
            this.loading = false;
            resolve();
          }
        });
      });
    },

    // 获取供应方式
    getSupplyType() {
      return new Promise((resove) => {
        dictMatching("inv_supply_type").then((res) => {
          if (res.code == 200) {
            this.optionsSupplyType = res.data;
          }
        });
        resove();
      });
    },

    // 获取物料数据
    getMaterialList(change) {
      this.reLoading = true;
      this.queryParams.sortRoot = this.paramSort.sortId.join(",");
      listMaterial(this.queryParams).then((res) => {
        if (res.code == 200) {
          this.basicfileList = res.rows;
          this.total = res.total;
          if (this.basicfileList.length >= 19) {
            //条数总数大于显示出现滚动条
            this.maxHeight = this.screenHeight - 270;
          } else {
            this.maxHeight = "";
          }
          this.reLoading = false;
        }
      });
    },

    //获取主计量数据
    getPacking() {
      this.reLoading = true;
      listUnit()
        .then((res) => {
          if (res.code == 200) {
            this.packingDate = res.rows;
            this.reLoading = false;
          }
        })
        .catch((err) => {
          this.msgError("获取主计量失败！");
        });
    },

    //物料分类点击获取
    nodeClick(node) {
      this.queryParams.name = ""; //避免当搜索物料信息时页面缓存物料名称
      this.queryParams.code = ""; //避免当搜索物料信息时页面缓存物料编码
      this.queryParams.type = true; //默认模糊查询
      this.queryParams.pageNum = 1; //默认页数
      this.queryParams.pageSize = 100; //默认条数
      this.butChange = "addStatus"; //按钮状态为新增
      this.upload2.sortId = node[0].sortId; //导入id
      this.disCuarent = false; //导入/导出/清空按钮状态
      this.transferData.unitCode = node[0].unitCode;
      this.transferData.sortId = node[0].sortId;
      // 获取上级分类名称
      const name = [];
      const getParentName = supParent(node[1], name).reverse(); //获取上级分类名称
      const parentName = getParentName.join(" / "); //拼接上级分类名称
      if (node[1].data.parentId == 0) {
        this.printName = node[1].data.sortName; //主类上级分类为自身
      } else {
        this.printName = parentName + " / " + node[1].data.sortName; //子类上级分类最终结果
      }
      this.isHeight = true; //打开分类树高亮
      this.queryParams.sortId = node[0].sortId; //赋值sortId用于搜索
      this.getMaterialList(); //重新拉取数据
    },

    // 查询所有
    checkleAll() {
      //清空搜索信息，避免干扰
      this.queryParams.sortId = "";
      this.queryParams.code = "";
      this.queryParams.name = "";
      this.printName = "";
      this.disCuarent = true;
      this.queryParams.type = true;
      this.serchReset(); //重置搜索表单
      this.isHeight = false; //关闭分类树高亮
      this.getMaterialList();
    },

    //搜索物料
    search() {
      if (
        this.searchForm.searchName == "" &&
        this.searchForm.searchCode == ""
      ) {
        this.msgError("物料编码或物料名称不能同时为空！");
      } else {
        this.queryParams.name = this.searchForm.searchName; //赋值物料名称
        this.queryParams.code = this.searchForm.searchCode; //赋值物料编码
        this.queryParams.type = true; //查询类型为模糊查询
        this.queryParams.sortId = ""; //避免当分类树点击时页面缓存的sortId导致搜索失败
        this.getMaterialList();
      }
    },

    // 物料表格头部编码搜索
    handleCodeName(status) {
      this.searchForm.searchName = ""; //清空头部搜索内容
      this.searchForm.searchCode = ""; //清空头部搜索内容
      if (status == "code") {
        //接收参数为code则为编码搜索
        this.inputStatusCode = true; //显示编码搜索框
        this.handleClose("name"); //关闭名称搜索框
      } else if (status == "name") {
        //接收参数为name则为名称搜索
        this.inputStatusName = true; //显示名称搜索框
        this.handleClose("code"); //关闭名称搜索框
      }
    },

    // 物料表格头部编码关闭
    handleClose(status) {
      if (status == "code") {
        this.inputStatusCode = false;
        this.headerFrom.codeInput = "";
      } else if (status == "name") {
        this.inputStatusName = false;
        this.headerFrom.nameInput = "";
      }
    },
    searchCodeName() {
      this.queryParams.name = this.headerFrom.nameInput; //赋值物料名称
      this.queryParams.code = this.headerFrom.codeInput; //赋值物料编码
      this.queryParams.type = false;
      this.inputStatusName = false;
      this.inputStatusCode = false;
      this.queryParams.sortId = ""; //避免当分类树点击时页面缓存的sortId导致搜索失败
      this.getMaterialList();
    },

    // 清空按钮操作
    handlEmpty() {
      this.$confirm(
        "是否清空" + " " + this.printName + " " + "物料信息?",
        "警告",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(() => {
          return emptyMaterial(this.upload2.sortId);
        })
        .then((res) => {
          this.msgSuccess("清空物料信息成功");
          this.getMaterialList();
          // this.disCuarent = true;
        });
    },

    // 导入按钮操作
    handleImport2() {
      this.upload2.title = this.printName + "导入";
      this.upload2.open = true;
    },

    // 文件上传中处理
    handleFileUploadProgress2(event, file, fileList) {
      this.upload2.isUploading = true;
    },

    // 文件上传成功处理
    handleFileSuccess2(response, file, fileList) {
      this.upload2.open = false;
      this.upload2.isUploading = false;
      this.$refs.upload2.clearFiles();
      this.$alert(response.msg, "导入结果", {
        dangerouslyUseHTMLString: true,
      });
      this.checkleAll();
    },

    // 提交上传文件
    submitFileForm2() {
      this.$refs.upload2.submit();
    },

    //导出农药基本档
    handleExportRelated() {
      const queryParams = this.queryParams;
      this.$confirm("是否确认导出所选物料数据项?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(function () {
          return exportRelatedMaterial(queryParams);
        })
        .then((response) => {
          this.download(response.msg);
        });
    },

    //导出零件基本档
    handleExportMach() {
      const queryParams = this.queryParams;
      this.$confirm("是否确认导出所选物料数据项?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(function () {
          return exportMachiningMaterial(queryParams);
        })
        .then((response) => {
          this.download(response.msg);
        });
    },

    // 打印
    handlePrint() {
      this.printData = this.basicfileList;
      let number = 1;
      this.printData = this.basicfileList;
      this.printData.forEach((obj) => {
        obj.id = number++;
      });
      setTimeout(() => {
        this.$print(this.$refs.startPrint.$refs.print);
      }, 0);
    },

    // 核名物料
    btnReview() {
      axios({
        methods: "get",
        url: this.effecUrl,
        params: {
          sortId: this.upload2.sortId,
        },
        headers: {
          Authorization: "Bearer " + getToken(),
        },
      }).then((res) => {
        this.$alert(res.data.msg, "核名结果", {
          dangerouslyUseHTMLString: true,
        });
      });
    },

    //查看物料
    seeMaterial(row) {
      this.butChange = "seeStatus"; //为1按钮状态为信息
      this.star = true;
      if (row.sortId !== this.upload2.sortId) {
        this.isSava = false; //不保存弹框回显数据
      }
      this.materialForm = Object.assign({}, row); //拷贝物料信息
      this.undataAddSee(row.sortId).then(() => {
        // 格式化4位小数
        let basicMount = JSON.parse(JSON.stringify(row));
        basicMount.lockQuantity = this.Decimal(basicMount.lockQuantity);
        basicMount.wayQuantity = this.Decimal(basicMount.wayQuantity);
        basicMount.quantity = this.Decimal(basicMount.quantity);
        if (
          basicMount.params.availableQuantity !== undefined &&
          basicMount.params.availableQuantity !== null
        ) {
          basicMount.params.availableQuantity = this.Decimal(
            basicMount.params.availableQuantity
          );
        } else {
          basicMount.params.availableQuantity = "0.0000";
        }

        this.materialMount = basicMount;
        this.open = true;
        this.packingForm = row.unitCode;
        this.dialogTitle = "物料信息";
        this.butChange = "seeStatus"; //改变表单状态
        this.alreadySelected = JSON.parse(
          JSON.stringify(this.materialForm.children)
        );
      });
    },

    // 新增/修改/查看公共获取分类回显
    undataAddSee(id) {
      return new Promise((resolve, reject) => {
        let parentArr = [], //用于储存父类分类信息
          childrenArr = []; ////用于储存子类分类信息
        getEcho(id, this.sortTree, parentArr, childrenArr).then((res) => {
          setTimeout(() => {
            let success = [];
            for (let i = 0; i < res.length; i++) {
              if (success.indexOf(res[i]) === -1) {
                success.push(res[i]);
              }
            }
            let getNode = JSON.parse(JSON.stringify(success)); //拷贝vuex信息，避免影响源数据
            getNode.forEach((v) => {
              if (v.ancestors.indexOf(",") > -1) {
                //是否是子分类
                v.ancestors = v.ancestors.split(",").length; //拼接数组长度，用于排序
              } else {
                v.ancestors = 1;
              }
            });
            getNode.sort((a, b) => {
              //排序得到正常的分类顺序，用于得到sortCode
              return a.ancestors - b.ancestors;
            });
            let getCode = [];
            getNode.forEach((code) => {
              getCode.push(code.sortCode);
              this.materialForm.sortId = code.sortId;
            });
            this.value = getCode; //对话框分类回显
            if (this.butChange == "addStatus") {
              //状态为新增物料
              getCode = getCode.join(""); //转换成字符串，用于传值后台
              this.materialForm.code = getCode;
            }
          }, 0);
        });
        resolve();
      });
    },

    //删除物料
    delMaterial(row) {
      this.$confirm("确认删除", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          return deleteMaterial(row.code);
        })
        .then((res) => {
          if (res.code == 200) {
            this.msgSuccess("删除成功");
            this.ids = [];
            this.getMaterialList();
            this.resetDilog(); //重置表单
          }
        });
    },

    // 关闭弹框
    closeDialog() {
      this.moreStatus = true;
      this.resetDilog();
      this.resetSelector();
    },

    //解决级联选择器回显高亮异常问题
    resetSelector() {
      if (this.$refs.classTree) {
        this.$refs.classTree.$refs.panel.activePath = [];
        this.$refs.classTree.$refs.panel.calculateCheckedNodePaths();
      }
    },

    //搜索表单重置
    serchReset() {
      for (let key in this.searchForm) {
        this.searchForm[key] = "";
      }
    },

    // 弹框新增清空表单
    resetFrom() {
      this.materialForm.name = ""; //物料名称清空
      this.materialForm.attribute = ""; //型号规格清空
      this.materialForm.initial = ""; //期初数量清空
      this.materialForm.price = ""; //期初单价清空
      this.materialForm.place = ""; //货位清空
      // this.packingForm = ""; //主计量清空
      this.materialMount = {};
      this.alreadySelected.forEach((obj) => {
        obj.relSortRoot = "";
        obj.relSortId = "";
        obj.relCode = "";
        obj.relName = "";
        obj.relAttribute = "";
        obj.relParam = "";
      });
    },

    // 弹框叉号关闭
    resetDilog() {
      if (this.isSava == false) {
        this.value = []; //重置分类
        this.materialForm.code = "";
      }
      this.keepName = false;
      this.resetFrom();
    },

    //弹框取消
    cancel() {
      this.open = false;
      this.moreStatus = true;
      this.resetDilog();
    },
  },

  components: {
    Tree,
    PrintPage,
  },
  watch: {
    screenHeight(newHeight) {
      if (this.basicfileList.length >= 19) {
        //条数总数大于显示出现滚动条
        this.maxHeight = newHeight - 270;
      } else {
        this.maxHeight = "";
      }
    },
  },
};
</script>
<style lang="scss">
.el-table {
  overflow: inherit;
}

.basicfile-box {
  .el-tree--highlight-current
    .el-tree-node.is-current
    > .el-tree-node__content {
    color: #1890ff;
  }

  .ma-right {
    .el-form-item {
      display: flex;
      align-items: center;
      justify-content: flex-end;
    }
    label {
      width: auto;
      flex-grow: 1;
    }

    .el-form-item__content {
      margin-left: 0px !important;
      margin-right: 0 !important;
    }
  }

  .height-tree2 {
    height: calc(100vh - 165px);
  }

  .el-table .el-table__header-wrapper th,
  .el-table .el-table__fixed-header-wrapper th {
    height: 35px;
  }

  .el-table__header,
  .el-table .cell,
  .basicfile-box .has-gutter th,
  .el-table thead {
    overflow: inherit !important;
  }

  // 下拉收起动画
  .toggle-fade {
    transition: all 0.1s linear;
    overflow: hidden;
  }

  .toggle-fade-enter-active {
    animation: downOpen 0.2s linear;
    overflow: hidden;
  }

  .toggle-fade-leave-active {
    animation: downOpen 0.2s reverse linear;
    overflow: hidden;
  }

  @keyframes downOpen {
    from {
      height: 0px;
    }

    to {
      height: 60px;
    }
  }

  .el-table tr td {
    cursor: pointer;
  }

  .txt-right {
    input {
      text-align: right;
    }
  }

  .el-table__header-wrapper,
  .el-table__footer-wrapper {
    overflow: inherit;
  }

  .operation-btn {
    .is-disabled {
      span {
        font-weight: 700;
      }
    }
  }

  .el-table--medium th,
  .el-table--medium td {
    overflow: inherit;
  }

  .el-table th > .cell {
    overflow: inherit;
    position: relative;
  }

  .caret-wrapper {
    position: absolute;
    right: 64px;
    top: -5px;
    display: none;
  }

  .el-button--info.is-plain.is-disabled {
    color: #adaeaf;
  }

  .search-box {
    .search-header {
      display: flex;
      align-items: center;
      justify-content: center;

      span {
        width: 65px;
        display: inline-block;
        flex-shrink: 0;
      }

      .el-input--mini .el-input__inner {
        padding-right: 10px;
        padding-left: 10px;
      }

      i {
        font-size: 14px;
        cursor: pointer;
      }

      .el-icon-close {
        font-size: 15px;
        color: #999;
      }
    }

    .box-input {
      position: absolute;
      top: 30px;
      z-index: 999;
      left: 0px;
      right: 0px;
      background: #fff;
      height: 60px;
      box-shadow: 1px 1px 5px #eee;

      .input-t {
        padding: 15px;
      }
    }
  }

  .cas-input input {
    color: #1890ff !important;
  }

  .keep-status {
    margin-top: 15px;
  }

  .updata-time {
    input {
      border: none;
    }
  }

  .el-cascader .el-input .el-input__inner {
    color: #1890ff;
  }

  .el-input--suffix input {
    color: #606266;
  }

  .el-cascader--medium {
    width: 100%;
  }

  .has-gutter th {
    text-align: center;
    overflow: inherit;
  }

  .el-dialog__body {
    padding-right: 20px;
    padding-bottom: 20px;
  }

  .now-stock {
    input {
      color: #1890ff !important;
    }
  }

  .now-actual input {
    color: #13ce66 !important;
  }

  .el-input.is-disabled .el-input__inner {
    color: #333;
  }

  .el-form-item--medium .el-form-item__content {
    margin-right: 10px;
  }

  .cell {
    padding-right: 14px !important;
    padding-left: 14px !important;

    .basic-delete {
      color: #f56c6c;
    }

    .basic-see {
      color: #67c23a;
    }

    button:hover i {
      font-weight: 700;
    }

    button:hover span {
      font-weight: 700;
    }
  }

  .from-mount {
    padding: 15px;
    box-shadow: 1px 1px 10px 1px #eee;
    border-radius: 5px;
    padding-bottom: 10px;
    margin: 10px 10px 0px 10px;

    h3 {
      font-weight: normal;
      font-size: 15px;
      margin-top: 0;
      text-align: center;
      color: #1890ff;
    }
  }

  .foot-bot {
    text-align: inherit !important;
    display: flex;
    justify-content: space-between;
    align-items: center;

    .foot-star {
      color: #1682e6;

      label {
        font-weight: normal;
        font-size: 12px;
      }
    }
  }
}
</style>
